<?php

namespace core\lib\schema;

use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\Table as SchemaTable;
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\Types\Type;
use support\Db;

class Table
{

    private SchemaTable $schemaTable;
    public function __construct(string $tablename)
    {
        $this->schemaTable =  Db::connection()->getDoctrineSchemaManager()
            ->introspectTable(getDatabasePrefix() . $tablename);
    }

    /**
     * 数据表描述
     *
     * @return string
     */
    public function getTableComment(): string
    {
        return $this->schemaTable->getOption('comment');
    }

    /**
     * 获取字段信息
     *
     * @return array
     */
    public function getColumns(): array
    {
        $primarys = $this->getPrimary();
        $arr = [];
        $columns = $this->schemaTable->getColumns();
        foreach ($columns as $key => $column) {
            $arr[] = [
                'autoincrement' => $column->getAutoincrement(),
                'primary'       => in_array($column->getName(), $primarys),
                'name'          => $column->getName(),
                'type'          => Type::lookupName($column->getType()),
                'length'        => $column->getLength(),
                'comment'       => $column->getComment()==null?'':$column->getComment(),
            ];
        }
        return $arr;
    }

    /**
     * 获取主键
     *
     * @return array
     */
    public function  getPrimary(): array
    {
        $indexs = $this->schemaTable->getPrimaryKey();
        return $indexs->getColumns();
    }
}
